// pages/order/orderDetail/orderDetail.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        orderId: 0,
        refundId: 0,
        detail: null,
        expressList: [],
        expressData: null,
        extractQrcode: '',
        isShowExtractQrcode: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.id) {
            this.data.orderId = options.id;
            this.setData({
                orderId: options.id
            });
        } else {
            this.data.refundId = options.refund_id;
            this.setData({
                refundId: options.refund_id
            });
        }

        this.onPullDownRefresh();

        // 增加订单被评价监听器
        wx.emitter.on('order.evaluate', this.onOrderEvaluate);
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        // 移除订单被评价监听器
        wx.emitter.off('order.evaluate', this.onOrderEvaluate);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        if (this.data.orderId) {
            this.loadDetail().finally(() => {
                wx.stopPullDownRefresh();
            });
        } else {
            this.loadRefundOrderDetail().finally(() => {
                wx.stopPullDownRefresh();
            });
        }
    },

    // 加载订单详情
    loadDetail: function () {
        return wx.http.post('api/user.order/detail', {
            order_id: this.data.orderId
        }).then((res) => {
            const detail = res.data.data.order;

            let goodsTotalPrice = wx.BigNumber('0.00');
            detail.goods.forEach(goods => {
                goodsTotalPrice = goodsTotalPrice.plus(goods.total_price);
                goods.discount_price = wx.BigNumber(goods.total_price).minus(goods.total_pay_price).toFixed(2, wx.BigNumber.ROUND_DOWN);
            });
            detail.goods_total_price = goodsTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN);

            this.setData({
                detail: detail,
            });

            // 是否加载物流信息
            if (detail.delivery_status.value === 20) {
                this.loadExpressDetail();
            }

            return detail;
        }, (err) => {
            console.warn("api/user.order/detail", err)
        });
    },

    // 加载退款订单详情
    loadRefundOrderDetail: function () {
        return wx.http.post('api/user.refund/detail', {
            order_refund_id: this.data.refundId
        }).then((res) => {
            const detail = res.data.data.detail;
            const expressList = res.data.data.expressList;
            const expresss = res.data.data.expresss;
            if (expresss) {
                expresss.data = expresss.list.reverse();
            }

            this.setData({
                detail: detail,
                expressList: expressList,
                expressData: expresss,
            });
            return detail;
        }, (err) => {
            console.warn("api/user.refund/detail", err)
        });
    },

    // 加载物流信息
    loadExpressDetail: function () {
        return wx.http.post('api/user.order/express', {
            order_id: this.data.orderId
        }).then((res) => {
            const detail = res.data.data;
            detail.data = detail.list.reverse();
            this.setData({
                expressData: detail
            });
            return detail;
        });
    },

    // 复制物流单号
    onCopyExpressNo: function (e) {
        const no = this.data.expressData.express_no;
        wx.setClipboardData({
            data: no,
            success(res) {
                wx.showToast({
                    title: '已复制！'
                });
            },
            fail(res) {
                wx.showToast({
                    title: '复制失败！',
                    icon: 'none'
                });
            }
        });
    },

    // 获取核销二维码
    extractQrcodeTap: function () {
        return wx.http.post('api/user.order/extractQrcode', {
            order_id: this.data.orderId
        }).then((res) => {
            const qrcode = res.data.data.qrcode;
            this.setData({
                extractQrcode: qrcode,
                isShowExtractQrcode: true
            });
            return qrcode;
        });
    },

    // 确认订单
    receiptTap: function () {
        wx.showModal({
            content: '你将确认订单，是否继续？',
            showCancel: true,
            success: (res) => {
                if (res.cancel) return;

                wx.http.post('api/user.order/receipt', {
                    order_id: this.data.orderId
                }, {
                        showLoading: true
                    }).then((res) => {
                        this.setData({
                            state_text: "已收货",
                            delivery_status: {
                                "text": "已收货",
                                "value": 20
                            }
                        });
                        wx.showToast({
                            title: '已收货！'
                        });
                        wx.navigateTo({
                            url: '/pages/user/order/evaluate/evaluate?id=' + this.data.orderId
                        })
                    });
            }
        });
    },

    // 取消订单
    cancelOrderTap: function (e) {
        wx.showModal({
            content: '取消后将不能恢复，你确定要取消订单吗？',
            showCancel: true,
            success: (res) => {
                if (res.cancel) return;

                wx.http.post('api/user.order/cancel', {
                    order_id: this.data.orderId
                }, {
                        showLoading: true
                    }).then((res) => {
                        this.setData({
                            state_text: "已取消",
                            order_status: {
                                "text": "已取消",
                                "value": 20
                            }
                        });
                        wx.showToast({
                            title: '已取消！'
                        });
                    });
            }
        });
    },

    // 去支付
    payOrderTap: function (e) {
        return wx.http.post('api/user.order/pay', {
            order_id: this.data.orderId
        }, {
                showLoading: true
            }).then((res) => {
                const payInfo = res.data.data.payment;
                return wx.promise.requestPayment({
                    timeStamp: payInfo.timeStamp,
                    nonceStr: payInfo.nonceStr,
                    package: 'prepay_id=' + payInfo.prepay_id,
                    signType: 'MD5',
                    paySign: payInfo.paySign,
                });
            }).then((res) => {
                wx.navigateTo({
                    url: '/pages/user/order/pay-success/pay-success?order_id=' + this.data.orderId
                })
            }, () => {
                wx.showToast({
                    title: '支付失败！',
                    icon: 'none'
                })
            });
    },

    // 取消退款
    cancelRefundTap: function () {
        wx.showModal({
            content: '取消后将不能恢复，你确定要取消订单吗？（没有接口）',
            showCancel: true,
            success: (res) => {
                if (res.cancel) return;

                wx.http.post('api/user.order/cancel', {
                    order_id: this.data.orderId
                }, {
                        showLoading: true
                    }).then((res) => {
                        // this.setData({
                        // 	state_text: "已取消",
                        // 	order_status: {
                        // 		"text": "已取消",
                        // 		"value": 20
                        // 	}
                        // });
                        wx.showToast({
                            title: '已取消！'
                        });
                    });
            }
        });
    },

    // 订单已被评价
    onOrderEvaluate: function (orderId) {
        const isCommentKey = `detail.is_comment`;
        const orderStatusKey = `detail.order_status`;
        this.setData({
            [isCommentKey]: 1,
            [orderStatusKey]: {
                text: "已完成",
                value: 30
            }
        });
    }
});